package com.cmq.web_1.employeemanage;


import com.cmq.web_1.employeemanage.UserDAO;
import com.cmq.web_1.employeemanage.UserDAOImpl;
import com.cmq.web_1.employeemanage.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/employeemanage/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private UserDAO userDAO;

    public void init() {
        userDAO = new UserDAOImpl();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 转发到登录页面
        request.getRequestDispatcher("/employeemanage/login.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = userDAO.login(username, password);

        if (user != null) {
            // 登录成功，将用户信息存入Session
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            // 重定向到仪表盘
            response.sendRedirect("dashboard");
        } else {
            // 登录失败，返回登录页面并显示错误信息
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("/employeemanage/login.jsp").forward(request, response);
        }
    }
}